# 所有和游戏运行有关的函数
import sys
import pygame
from bullet import Bullet
from alien import Alien
import time

def fire_bullet(ai_settings,screen,ship,bullets):
    if len(bullets) < ai_settings.bullet_allowed:
        new_bullet = Bullet(ai_settings,screen,ship)
        bullets.add(new_bullet)
# 按左右键，实现飞船移动
def check_keydown_events(event,ai_settings,screen,ship,bullets):  #响应按键按下
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    if event.key == pygame.K_LEFT:
        ship.moving_left = True
    if event.key == pygame.K_SPACE:
            fire_bullet(ai_settings,screen,ship,bullets)

def check_keyup_events(event,ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False

def check_events(ai_settings, screen, stats,sb, play_button, ship, aliens,bullets):
    # 检查所有事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN :
            check_keydown_events(event,ai_settings,screen,ship,bullets)
        elif event.type == pygame.KEYUP :
            check_keyup_events(event,ship)
        elif event.type == pygame.MOUSEBUTTONDOWN :
            # 获取鼠标按下后的坐标
            mouse_x,mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, play_button, ship, aliens,bullets, mouse_x, mouse_y,sb)

def check_play_button(ai_settings, screen, stats, play_button, ship, aliens,bullets, mouse_x, mouse_y,sb):
    if play_button.rect.collidepoint(mouse_x,mouse_y) and not stats.game_active:
        # 隐藏光标
        pygame.mouse.set_visible(False)
        # 重置游戏速度
        ai_settings.initialize_dynamic_settings()
        # 重置游戏状态
        stats.game_active = True
        stats.reset_stats()
        # 重置记分牌图像
        sb.prep_score()
        sb.prep_high_score()
        sb.prep_level()
        sb.prep_ships()
        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()
        # 创建一群新的外星人，并让飞船居中
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

def update_screen(ai_settings,screen,stats,ship,bullets,alines,play_button,sb):
    screen.fill(ai_settings.bg_color)    # 设置背景色
    # 画出得分
    sb.show_score()
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()   # 画出飞船
    alines.draw(screen) # 画出外星人
    # 如果游戏处于非活动状态，就绘制Play按钮
    if stats.game_active == False:
        play_button.draw_button()
        # 隐藏光标
        pygame.mouse.set_visible(True)
    pygame.display.flip()    # 显示屏幕


def check_bullet_alien_collisions(ai_settings, screen,stats,sb, ship, aliens, bullets):
    # 检查是否有子弹击中了外星人
    # 如果是这样，就删除相应的子弹和外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            sb.prep_score()
        check_high_score(stats, sb)
    # 消灭完后重新生成一批外星人
    if len(aliens) == 0:
        # 删除现有的子弹并新建一群外星人
        bullets.empty()
        ai_settings.increase_speed()
        # 提高等级
        stats.level += 1
        sb.prep_level()
        create_fleet(ai_settings, screen, ship, aliens)

def update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets):
    bullets.update()  # 更新子弹
    # 删除应该消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets)


# 创建一群外星人
def  get_number_col(ai_settings,alien_width):
    # 可用空间x
    available_space_x = ai_settings.screen_width - 2*alien_width
    # 一行画几个
    number_aliens_x = int(available_space_x / (2*alien_width))
    return number_aliens_x

# 计算总共有几行
def get_number_row(ai_settings, ship_height, alien_height):
    available_space_y = (ai_settings.screen_height -(3 * alien_height) - ship_height)
    number_alien_y = available_space_y / (alien_height*2)
    return number_alien_y

def create_alien(ai_settings, screen, aliens, alien_number_x,alien_number_y):
    alien = Alien(ai_settings,screen)
    alien_width = alien.rect.width
    alien_height = alien.rect.height
    alien.x = alien_width + 2 * alien_width * alien_number_x
    alien.rect.x = alien.x
    alien.y = alien_height + 2 * alien_height * alien_number_y
    alien.rect.y = alien.y
    aliens.add(alien)

def create_fleet(ai_settings,screen,ship,aliens):
    alien = Alien(ai_settings,screen)
    number_aliens_col = get_number_col(ai_settings,alien.rect.height)
    number_aliens_row = get_number_row(ai_settings,ship.rect.height,alien.rect.height)
    # 创建一行外星人
    for row in range(0,int(number_aliens_row)):
        for col in range(0,int(number_aliens_col)):
            create_alien(ai_settings, screen, aliens, col,row)
# 更新外星人
def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
    check_fleet_edges(ai_settings,aliens)
    for alien in aliens:
        alien.update()
    #  检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
    check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets) # 检查外星人是否没和飞船碰撞但到达底部



def check_fleet_edges(ai_settings,aliens):
    for alien in aliens:
       if alien.check_edges():
           change_feet_direction(ai_settings,aliens)
           break


def change_feet_direction(ai_settings,aliens): # 外星人改变方向
    for alien in aliens:
        alien.rect.y = alien.rect.y + ai_settings.feet_drop_speed

    ai_settings.feet_direction *= -1

#碰到飞船后重开
def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets):
    # ""响应被外星人撞到的飞船"""
    if stats.ships_left >0:
        # 将ships_left减1
        stats.ships_left -= 1
        # 更新记分牌
        sb.prep_ships()
    else:
        stats.game_active = False
        time.sleep(1)
        # 清空外星人列表和子弹列表
    aliens.empty()
    bullets.empty()
    # 创建一群新的外星人，并将飞船放到屏幕底端中央
    create_fleet(ai_settings, screen, ship, aliens)
    ship.center_ship()
    # 外星人与飞船碰撞后暂停时间
    time.sleep(0.5)

# 检查外星人是否没和飞船碰撞但到达底部
def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets):
    screen_rect = screen.get_rect()
    for alien in aliens:
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)
            break


def check_high_score(stats, sb):
    # 检查是否诞生了新的最高得分
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()
